package com.itrident.loader.imlp;

import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.template.CustomLiveTemplateBase;
import com.intellij.codeInsight.template.impl.CustomLiveTemplateLookupElement;
import com.intellij.openapi.project.Project;
import com.itrident.loader.AbstractLoader;
import com.itrident.store.EnumsInfo;
import com.itrident.store.EnumsManagerPersistentState;
import com.itrident.store.EnumsWrapper;

import java.util.ArrayList;
import java.util.List;

import static com.itrident.impl.XmlEnumLiveTemplate.TIPS;

/**
 * @author cxx
 * @create 2021-04-15 17:19
 **/
public class XmlEnumsLoader extends AbstractLoader {

    private Project project;

    protected XmlEnumsLoader(CustomLiveTemplateBase ctb) {
        super (ctb);
    }

    public XmlEnumsLoader(CustomLiveTemplateBase ctb, Project project) {
        super (ctb);
        this.project = project;
    }

    @Override
    public List<LookupElement> load(String prefix) {
        EnumsManagerPersistentState persistentState = EnumsManagerPersistentState.getInstance (this.project);
        List<EnumsWrapper> enumsWrapper = persistentState.getEnumsWrapper ();
        List<LookupElement> lookupElements = new ArrayList<> ();
        for (EnumsWrapper wrapper : enumsWrapper) {
            List<EnumsInfo> enumsInfos = wrapper.getEnumsInfos ();
            for (EnumsInfo enumsInfo : enumsInfos) {
                if(prefix.startsWith (TIPS)){
                    prefix = prefix.substring (1);
                }
                if (isMatch(enumsInfo.getCode (),prefix)){
                    CustomLiveTemplateLookupElement lookupElement = new CustomLiveTemplateLookupElement (ctb, enumsInfo.getCode ()
                            ,enumsInfo.getCode (), enumsInfo.getDesc (), false, true);
                    lookupElements.add (lookupElement);
                }
            }
        }
        return lookupElements;
    }

    private boolean isMatch(String code,String prefix){
        if ("".equals (prefix)) {
            return true;
        }
        for (char c : prefix.toLowerCase ().toCharArray ()) {
            if (!isPrefixMatch (code, c)){
                return false;
            }
        }
        return true;
    }

    private boolean isPrefixMatch(String prefix, char c) {
        for (char c1 : prefix.toLowerCase ().toCharArray ()) {
            if (c == c1) {
                return true;
            }
        }
        return false;
    }
}
